package com.ruoyi.common.utils;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Base64;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;

public class KeyGeneratorByPKCS {
    public static void main(String[] args) {
        try {
            // 创建 KeyPairGenerator 实例，指定算法为 RSA
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            // 初始化 KeyPairGenerator，指定密钥长度为 1024 位
            keyPairGenerator.initialize(1024);
            // 生成密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            // 获取公钥和私钥
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            // 将公钥和私钥转换为 PKCS#8 格式
            byte[] publicKeyBytes = publicKey.getEncoded();
            byte[] privateKeyBytes = privateKey.getEncoded();
            // 使用 Base64 编码密钥以便于显示
            String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKeyBytes);
            String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKeyBytes);
            System.out.println("Public Key (PKCS#8): " + publicKeyBase64);
            System.out.println("Private Key (PKCS#8): " + privateKeyBase64);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeKeyToPemFile(java.security.spec.EncodedKeySpec keySpec, String fileName) throws IOException {
        try (FileWriter fileWriter = new FileWriter(fileName);
             PemWriter pemWriter = new PemWriter(fileWriter)) {

            String type = keySpec instanceof X509EncodedKeySpec ? "PUBLIC KEY" : "PRIVATE KEY";
            PemObject pemObject = new PemObject(type, keySpec.getEncoded());
            pemWriter.writeObject(pemObject);
        }
    }
}
